#include <iom128.h>
#include <inavr.h>  //delay_cycles
#include "config.h"
#include "opcmd.h"
#include "ds18b20.h"
#include "uart.h"
#include "bitop.h"
//#include "ds18b20_new.h"
#include "flash.h"
#include "alloc.h"
#include "list.h"
#include "self_programming.h"

#define MAST_CMD_DEBUG		1

#define FLAG_PACK_START		0x0B
#define FLAG_PACK_INTE		0x0B
#define FLAG_PACK_END		0x0D
#define FLAG_PACK_ERR		0x0E



//static u16 			g_cur_write_flash_page;// = FLASH_ADDR_SUPER_BLOCK+1;

static list_t 		g_mapping_list;
static st_flash_sb 	g_flash_sb;
static st_enum_ctrl	g_enum_ctrl;

u08*	g_buff_handle_master = NULL;


s16 write_funit_to_flash(st_enum_ctrl*p_enum_ctrl)
{
	u08 cnt,i,memlen;
	u08*ptmp = NULL;
	u08 ptmp_offset = 0;
	s16 ret = 0;
	u08*psrc;

	u32 addr;
	list_node_t* pnode;
	st_sensor_fdata* sensor;
	list_t*plist;

	plist = &p_enum_ctrl->list;

	cnt = (u08)list_get_count(plist);

	if(cnt == 0)
	{
		return -1;
	}
	if(cnt!=FUNIT_COUNTS_PER_PAGE)
	{
		F(("w_wf\r\n")); //shoud occur in the last page
	}
	//--------------------------------------------------alloc memory
	memlen = cnt*sizeof(st_sensor_funit);
	ptmp = user_malloc_alloc(memlen+1);
	if(ptmp==NULL)
	{
		return -2;
	}
	for(i = 0;i<memlen;i++)
		ptmp[i] = 0x00;
	//--------------------------------------------------	

	addr = p_enum_ctrl->cur_page*(u32)FLASH_PAGE_SIZE;
    //F(("fa:%x %x %lx \r\n",p_enum_ctrl->cur_page,FLASH_PAGE_SIZE,addr));
    
	ptmp[ptmp_offset++]=cnt;	//save the page date to ptmp,and write flash once	
	for (pnode = list_begin(plist); pnode != list_end(plist);pnode = list_next(pnode))
	{
		sensor = entry_list(pnode, st_sensor_fdata, node);
		psrc = (u08*)(&sensor->funit);
		for(i = 0;i<sizeof(st_sensor_funit);i++)
		{
			ptmp[ptmp_offset++] = psrc[i];
		}
	}
    
    //F(("fb:%lx\r\n",addr));

	if(WriteFlashPage(addr,ptmp) == FALSE)
	{
        user_malloc_free(ptmp);
        F(("e_wf1\r\n"));
		return -3;
	}

	
    p_enum_ctrl->cur_page++;
    
	user_malloc_free(ptmp);

	return ret;
}

//----------------------------------------------------------
// next 2 function for wrapping the ds18b20
//----------------------------------------------------------
s16 w1_enum_devices( st_enum_ctrl*p_enum_ctrl )
{

	u08 id[8], i,diff;
	u08 port_num = p_enum_ctrl->io_idx;
	s16 scount = 0;
	s16 ret;
	st_sensor_fdata*sf;

	//-----------------------------------------------------------
	for( diff = SEARCH_FIRST; diff != LAST_DEVICE; )
	{
		diff = w1_rom_search( port_num, diff, id );

		if( diff == PRESENCE_ERR )
		{
			scount = -1;
			break;
		}
		if( diff == DATA_ERR )
		{
			scount = -2;
			break;
		}
		if( id[0] == 0x28 )   // temperature sensor
		{			
			sf = mempool_sensor_fdata_get();
			if(sf==NULL)
			{			
				ret = write_funit_to_flash(p_enum_ctrl);	//write flash
				if(ret!=ERR_NO_ERR)
				{
					scount = -4;
					break;
				}
				//---------------------------------
				list_init(&p_enum_ctrl->list);				//reinit the mempool
				mempool_sensor_fdata_init(p_enum_ctrl->paddr,FUNIT_COUNTS_PER_PAGE);
				sf = mempool_sensor_fdata_get();	

			}

			w1_byte_wr( port_num, READ );	// read command
			w1_byte_rd( port_num );			// low byte
			w1_byte_rd( port_num );			// high byte

			sf->funit.flag = 1;
			sf->funit.y_idx = w1_byte_rd( port_num );	// user th,sid for the sensor
			sf->funit.y_idx &=0x3f;
			sf->funit.x_idx = w1_byte_rd( port_num );
			sf->funit.io_idx = port_num;
			for(i = 0;i<8;i++)
				sf->funit.romid[i]=id[i];

			list_insert_back(&p_enum_ctrl->list,&sf->node);

			scount++;
            
            p_enum_ctrl->sensor_cnt++;
                
#if(MAST_CMD_DEBUG==1)
			F(("id:%x_%x:%x %x %x %x %x %x %x %x\r\n",	sf->funit.x_idx,
						sf->funit.y_idx,
						id[0],id[1],id[2],id[3],
						id[4],id[5],id[6],id[7]
			  ));
#endif
		}
	}

	return scount;
}


s16 w1_send_command2( u08 port_num,u08 command, u08*romid)
{
	u08 i;
	u08 err = 0;
	u08 count = 1;
	u08*id=romid;

	while(count--)
	{
		err = w1_reset( port_num);
		if(err == ERR_NO_ERR)
			break; 
		delayms(10);
	}

	if( err )
	{
		F(("e_cmd2:%d\r\n",port_num));
		return -1;		
	}


	if( id )
	{
		w1_byte_wr( port_num,MATCH_ROM );
		i = 8;
		do
		{
			w1_byte_wr( port_num,*id );
			id++;
		}
		while( --i );
	}
	else
	{
		w1_byte_wr( port_num,SKIP_ROM );			// send rom command
	}

	w1_byte_wr( port_num,command );					//send function command

	return ERR_NO_ERR;
}

u08 read_config_from_sensor(u08 port_num,u08* romid)
{
	u08 config;
	u08 val;
	w1_send_command2( port_num,READ, romid );

	w1_byte_rd(port_num);
	w1_byte_rd(port_num);
	w1_byte_rd(port_num);
	w1_byte_rd(port_num);

	config = w1_byte_rd(port_num);
	val=(config&0x60)>>5;

	return val;
}
   
       
    
u08 read_temp_from_sensor(u08 port_num,u08* romid)
{
    u08 temp_h,temp_l,temp;

	w1_send_command2(port_num,CONVERT_T,romid);      
	delayms(TIME_FOR_MEAS); //750,375,187.5,93.5
	__clear_watchdog_timer(); 

    w1_send_command2(port_num,READ,romid);
    temp_l = w1_byte_rd( port_num );
    temp_h = w1_byte_rd( port_num );
    
    temp = (temp_h&0x80)|((temp_h&0x03)<<5)|(temp_l>>3);

    return temp;
}


//--------------------------------------------------------------
//	the packet format:
//					offset
//	length			0
//	status			1
//	xidx			2
//	payload				
//	payload2		
//	.				.
//	.
//	.
//	payloadn



/*
   typedef struct _st_sensor_funit
   {
   u08	flag;
   u08	io_idx;
   u08	x_idx;
   u08	y_idx;
   u08	romid[8];
   }st_sensor_funit;

   typedef struct _st_sensor_munit
   {
   u08	x_idx;
   u08	y_idx;
   u16	rom_addr;
   }st_sensor_munit;

   typedef struct __st_xidx_list
   {
   u08		xidx;
   list_t	list;
   list_node_t	node;
   }st_xidx_list;


*/
/*
   one flash page
//-----------------
//		scnt 				//sensor cnts in this page
//		io_idx		----|
//		x_idx			|
//		y_idx			|
//		rom_id[0]		|-->the fisrt unit(st_sensor_funit)
//		rom_id[1]		|
//		.				|
//		.				|
//		rom_id[7]	----|
//		io_idx		----|
//		x_idx			|
//		y_idx			|
//		rom_id[0]		|-->the sencond unit
//		rom_id[1]		|
//		.				|
//		.				|
//		rom_id[7]	----|
.
.
.
//-------------------

st_xidx_list xlistn,link the st_sensor_munit with the same xidx(column number)

g_mapping_list.head
|
xlist1.head<->sm1<->sm2<->.....smN<->xlist1.tail
|
xlist2
|
xlist3
|
xlist4
|
.
.
xlistn
|
.
.
|
g_mapping_list.tail

*/
void debug_mapping_list(void)
{
	u08	cnt = 0;

	list_node_t* pnode;
	st_xidx_list* xlist;

	list_node_t*pnode1;
	st_sensor_mdata* sm;

    cnt = list_get_count(&g_mapping_list);
    //F(("maping cnt:%d\r\n",cnt));
    
	for (pnode = list_begin(&g_mapping_list); pnode != list_end(&g_mapping_list);pnode = list_next(pnode))
	{
		xlist = entry_list(pnode, st_xidx_list, node);
		//F(("xidx = %d cnt = %d\r\n",xlist->xidx,xlist->scnt));

		cnt = 0;
		for (pnode1 = list_begin(&xlist->list); pnode1 != list_end(&xlist->list);pnode1 = list_next(pnode1))
		{
			sm = entry_list(pnode1, st_sensor_mdata, node);
			F(("[%d] io_x_y_addr[%d][%d][%d][%d]\r\n",cnt,sm->munit.io_idx,xlist->xidx,sm->munit.y_idx,sm->munit.rom_addr));
			cnt++;
		}
	}

	return;
}
st_xidx_list* list_find_xidx(u08 xidx)
{
	list_node_t* pnode;
	st_xidx_list* xlist = NULL;
	st_xidx_list* ret = NULL;

	for (pnode = list_begin(&g_mapping_list); pnode != list_end(&g_mapping_list);pnode = list_next(pnode))
	{
		xlist = entry_list(pnode, st_xidx_list, node);
		if(xlist->xidx == xidx)
		{
			ret = xlist;
			break;
		}
	}
	return ret;
}

list_node_t*find_best_position(list_t*plist,u08 yidx)
{
	list_node_t* pnode;
	st_sensor_mdata*	sm;
	list_node_t* ret = NULL;

	for (pnode = list_begin(plist); pnode != list_end(plist);pnode = list_next(pnode))
	{
		sm = entry_list(pnode, st_sensor_mdata, node);
		if(yidx <= sm->munit.y_idx)
		{
			ret = &sm->node;
			break;
		}
	}
	return ret;
}

void create_mapping_from_flash(st_flash_sb*sb)
{
	u08*ptmp,xidx,scnt,sidx;
	u16 page_idx;
	u32 addr;
	st_sensor_mdata	*sm;
	st_xidx_list	*p_xlist;
	list_node_t	*pnode;
	for(page_idx = sb->page_start; page_idx <= sb->page_end; page_idx++)
	{
		addr = page_idx*(u32)FLASH_PAGE_SIZE;		
		scnt = ReadFlashByte(addr++);
        
        //F(("scnt=0x%x\r\n",scnt));
        if(scnt>FUNIT_COUNTS_PER_PAGE)
        {
            continue;
        }
        
		for(sidx=0;sidx<scnt;sidx++)
		{
			sm = mempool_sensor_mdata_get();
			if(sm==NULL)
			{
				ptmp = user_malloc_alloc(MUNIT_COUNTS_PER_PAGE*sizeof(st_sensor_mdata));
				if(ptmp==NULL)
				{
					F(("e_crt_mp1\r\n"));
					return;
				}
                //F(("ac1:%x\r\n",MUNIT_COUNTS_PER_PAGE*sizeof(st_sensor_mdata)));
				mempool_sensor_mdata_init(ptmp,MUNIT_COUNTS_PER_PAGE);				
				sm = mempool_sensor_mdata_get();
			}

			ReadFlashByte(addr++);						//flag	
			sm->munit.io_idx = ReadFlashByte(addr++);	//io
			//if(sm->munit.io_idx >= 8)
			//	continue;
			xidx = ReadFlashByte(addr++);			//x
			sm->munit.y_idx = ReadFlashByte(addr++);//y
			sm->munit.rom_addr = (u16)(addr-(FLASH_SIZE>>1));
            
            addr += 8;  //rom addr
            
            //F(("xidx = 0x%x yidx = 0x%x\r\n",xidx,sm->munit.y_idx));
            
			p_xlist = list_find_xidx(xidx);
            
			if(p_xlist == NULL)
			{
				p_xlist = (st_xidx_list*)user_malloc_alloc(sizeof(st_xidx_list));
				if(p_xlist==NULL)
				{
					F(("e_crt_mp2\r\n"));
					break;
				}
                //F(("ac2:%x\r\n",sizeof(st_xidx_list)));
				p_xlist->xidx = xidx;
				p_xlist->scnt = 0;
				list_init(&p_xlist->list);
				list_insert_back(&g_mapping_list,&p_xlist->node);

				list_insert_back(&p_xlist->list,&(sm->node));
			}
			else
			{
				//sort the sm with y_idx
				pnode = find_best_position(&p_xlist->list,sm->munit.y_idx);
				if(pnode)
				{
					list_insert_before(pnode,&sm->node);
				}
				else
				{
					list_insert_back(&p_xlist->list,&sm->node);
				}
			}

			p_xlist->scnt++;
		}				
	}
}

s16 enum_init(st_enum_ctrl*p_enum_ctrl)
{
	p_enum_ctrl->io_idx = 0xff;
	p_enum_ctrl->sensor_cnt = 0x00;
	p_enum_ctrl->cur_page = FLASH_ADDR_SUPER_BLOCK+1;
	list_init(&p_enum_ctrl->list);

	p_enum_ctrl->paddr = user_malloc_alloc(sizeof(st_sensor_fdata)*FUNIT_COUNTS_PER_PAGE);
	if(p_enum_ctrl->paddr==NULL)
	{
		return -1;
	}
	mempool_sensor_fdata_init(p_enum_ctrl->paddr,FUNIT_COUNTS_PER_PAGE);

	return ERR_NO_ERR;
}

s16 enum_deinit(st_enum_ctrl*p_enum_ctrl)
{
	p_enum_ctrl->io_idx = 0xff;
	list_init(&p_enum_ctrl->list);
	if(p_enum_ctrl->paddr)
	{
		user_malloc_free(p_enum_ctrl->paddr);
		p_enum_ctrl->paddr = NULL;
	}

	return 0;
}

s16 enum_modify_resolution(u08 res)
{

	u08 id[8],ret,port_num,th,tl,config;
	u32 addr;	 
	list_node_t* pnode;
	st_xidx_list* xlist;

	list_node_t*pnode1;
	st_sensor_mdata* sm;

	for (pnode = list_begin(&g_mapping_list); pnode != list_end(&g_mapping_list);pnode = list_next(pnode))
	{
		xlist = entry_list(pnode, st_xidx_list, node);		 
		for (pnode1 = list_begin(&xlist->list); pnode1 != list_end(&xlist->list);pnode1 = list_next(pnode1))
		{
			sm = entry_list(pnode1, st_sensor_mdata, node);

			port_num = sm->munit.io_idx;
			addr = (u32)sm->munit.rom_addr+(FLASH_SIZE>>1);
			//F(("mr:%lx\r\n",addr));
			for(ret = 0;ret<8;ret++)
			{
				id[ret] = ReadFlashByte(addr++);	//get rom id
			}
			//--------------------------------------------------read
			ret = w1_send_command2(sm->munit.io_idx,READ,id);
			if(ret!=ERR_NO_ERR)
			{
				F(("e_r_cfg\r\n"));
				continue;
			}
			w1_byte_rd(port_num);
			w1_byte_rd(port_num);
			th = w1_byte_rd(port_num);
			tl = w1_byte_rd(port_num);
			config = w1_byte_rd(port_num);
			if(((config&0x60)>>5)==(res-9))
			{
                //F(("same\r\n",addr));
				continue; //no need modify
			}
			//--------------------------------------------------modify
			//F(("conf:%x\r\n",config));
			config &= ~(0x60);
			config |= ((res-9)<<5);
			F(("conf:0x%x\r\n",config));
			//-------------------------------------------------write to sram,not e2
			//for optimal,if the the config val is same,no need to send write cmd.
			ret = w1_send_command2(port_num,WRITE,id);
			if(ret!=ERR_NO_ERR)
			{
				F(("e_w_cfg\r\n"));
				continue;
			}

			w1_byte_wr(port_num,th);
			w1_byte_wr(port_num,tl);
			w1_byte_wr(port_num,config);
			
			//-------------------------------------------------write to e2
			//for optimal,if the the config val is same,no need to send write cmd.
			ret = w1_send_command2(port_num,EE_WRITE,id);
			if(ret!=ERR_NO_ERR)
			{
				F(("e_w2_cfg\r\n"));
				continue;
			}
		}
	}

	return ERR_NO_ERR;
}

s16 master_cmd_init(void)
{
	list_node_t* pnode;
	st_xidx_list* xlist;
	u08 xidx_cnt;
	u16 len = 0;

	xidx_cnt = list_get_count(&g_mapping_list);
	for (pnode = list_begin(&g_mapping_list); pnode != list_end(&g_mapping_list);pnode = list_next(pnode))
	{
		xlist = entry_list(pnode, st_xidx_list, node);
		len+= xlist->scnt;
	}
	len +=xidx_cnt*3;

    /*
	if(g_buff_handle_master)
	{
		F(("****\r\n"));
		user_malloc_free(g_buff_handle_master);
		F(("####\r\n"));
		g_buff_handle_master = NULL;
	}
    */
    
	g_buff_handle_master = user_malloc_alloc(len);
	if(g_buff_handle_master == NULL)
	{
		F(("e_buf_mst:0x%x\r\n",len));
		return -1;
	}
	return ERR_NO_ERR;
}

#if 0
void test_flash_wr(void)
{
	u08* paddr,*paddr2;
 	//test for flash read and write
	paddr = user_malloc_alloc(FLASH_PAGE_SIZE);
	if(paddr==NULL)
	{
		F(("e_all\r\n"));
		return -1;
	}
	for(i = 0;i<255;i++)
		paddr[i] = i;

    if(WriteFlashPage(0x6000,paddr) == FALSE)
	{
		F(("wferr\r\n"));
		return -2;
	}	
	F(("wfok\n"));
	paddr2 = user_malloc_alloc(FLASH_PAGE_SIZE);
	if(paddr2==NULL)
	{
		F(("e_all2\r\n"));
		return -3;
	}
	ReadFlashPage(0x6000,paddr2);
	for(i = 0;i<255;i++)
	{
		if(paddr[i]^paddr2[i])
			F(("%x[*] %x %x\r\n",i,paddr[i],paddr2[i]));
        else
   			F(("%x[#] %x %x\r\n",i,paddr[i],paddr2[i]));
	}

    user_malloc_free(paddr);
    user_malloc_free(paddr2);
    
    return;
}
#endif

s16 sensor_sys_init(u08 force_flag)
{
	u08	i;
	s16 ret;

	user_malloc_init();			//malloc init
	mempool_deinit();

	list_init(&g_mapping_list);
#if 0	
    test_flash_wr();
#endif
	flash_sb_init(&g_flash_sb);	//read system status
    
	if((g_flash_sb.programed != FLAG_FLASH_PROGRAMED) || force_flag)	//need enumerate all the io
	{
		ret = enum_init(&g_enum_ctrl);
		if(ret!=ERR_NO_ERR)
		{
			F(("e_enum_init\r\n"));
			return ret;
		}

		for(i=0; i<GPIO_PINS_IN_USE; i++)
		{	
			g_enum_ctrl.io_idx = i;
            
			ret = w1_enum_devices(&g_enum_ctrl);

#if(MAST_CMD_DEBUG==1)
			F(("---io %x---cnt %d\r\n",i,ret));
#endif	
		}
        //-----------------------------------------------       
        write_funit_to_flash(&g_enum_ctrl); //if has some sensors remain in one page
        
        //----------------------------------------------- //write superblock
		g_flash_sb.page_end = g_enum_ctrl.cur_page-1;
		g_flash_sb.sensor_cnt = g_enum_ctrl.sensor_cnt;
		ret = flash_sb_rewrite(&g_flash_sb);
		if(ret!=ERR_NO_ERR)
		{
			F(("e_sb_w\r\n"));
			return ret;
		}
        //-----------------------------------------------		
		enum_deinit(&g_enum_ctrl);
        
	}

	//need read flash and creat the mapping				
	create_mapping_from_flash(&g_flash_sb);
    enum_modify_resolution(RESOLUTION_SENSOR_DEFAULT);
    
#if(MAST_CMD_DEBUG==1)
	debug_mapping_list();
	debug_heap();
#endif

	master_cmd_init();

	return ERR_NO_ERR;
}
//-------------------------------------------------------------- 0x60
s16 handle_cmd_querry_sensors(u08*in_buf,u08*out_buf,u16*ret_len)
{
	u16 cur_off = 0;

	list_node_t* pnode;
	st_xidx_list* xlist;

	list_node_t*pnode1;
	st_sensor_mdata* sm;

	if((in_buf[1]!=0xFF)||(in_buf[2]!=0xFF))
	{
		return -1;
	}

	if(g_buff_handle_master == NULL)
	{
		return -2;
	}
	
	for (pnode = list_begin(&g_mapping_list); pnode != list_end(&g_mapping_list);pnode = list_next(pnode))
	{
		xlist = entry_list(pnode, st_xidx_list, node);

		g_buff_handle_master[cur_off++] = xlist->scnt+2;

		if(pnode == list_front(&g_mapping_list))
			g_buff_handle_master[cur_off++] = FLAG_PACK_START;
		else if(pnode == list_back(&g_mapping_list))
			g_buff_handle_master[cur_off++] = FLAG_PACK_END;
		else 
			g_buff_handle_master[cur_off++] = FLAG_PACK_INTE;

		g_buff_handle_master[cur_off++] = xlist->xidx;
		
		for (pnode1 = list_begin(&xlist->list); pnode1 != list_end(&xlist->list);pnode1 = list_next(pnode1))
		{
			sm = entry_list(pnode1, st_sensor_mdata, node);
			g_buff_handle_master[cur_off++] = sm->munit.y_idx;
		}
	}
	
	*ret_len = cur_off;
	
	return ERR_NO_ERR;
}

//--------------------------------------------------------------0x62
s16 handle_cmd_search_sensors(u08*in_buf,u08*out_buf,u16*ret_len)
{
	s16 ret;

	if((in_buf[1]!=0xFF)||(in_buf[2]!=0xFF))
	{
		return -1;
	}

	if(g_buff_handle_master == NULL)
	{
		return -2;
	}

	g_buff_handle_master[0] = 0x01;
	g_buff_handle_master[1] = 0x0D;

	ret = sensor_sys_init(1);
	if(ret!=ERR_NO_ERR)
	{
		g_buff_handle_master[1] = 0x0E;
	}

	*ret_len = 0x02;

	return ERR_NO_ERR;
}

//--------------------------------------------------------------0x64

s16 handle_cmd_read_config(u08*in_buf,u08*out_buf,u16*ret_len)
{
	u08	romid[8],i,port_num,config;
	u16 cur_off = 0;
	u32	addr;

	list_node_t* pnode;
	st_xidx_list* xlist;

	list_node_t*pnode1;
	st_sensor_mdata* sm;

	if((in_buf[1]!=0xFF)||(in_buf[2]!=0xFF))
	{
		return -1;
	}

	if(g_buff_handle_master == NULL)
	{
		return -2;
	}
	
	for (pnode = list_begin(&g_mapping_list); pnode != list_end(&g_mapping_list);pnode = list_next(pnode))
	{
		xlist = entry_list(pnode, st_xidx_list, node);

		g_buff_handle_master[cur_off++] = xlist->scnt+2;

		if(pnode == list_front(&g_mapping_list))
			g_buff_handle_master[cur_off++] = FLAG_PACK_START;
		else if(pnode == list_back(&g_mapping_list))
			g_buff_handle_master[cur_off++] = FLAG_PACK_END;
		else 
			g_buff_handle_master[cur_off++] = FLAG_PACK_INTE;

		g_buff_handle_master[cur_off++] = xlist->xidx;
		
		for (pnode1 = list_begin(&xlist->list); pnode1 != list_end(&xlist->list);pnode1 = list_next(pnode1))
		{
			sm = entry_list(pnode1, st_sensor_mdata, node);

			addr = (u32)sm->munit.rom_addr+(FLASH_SIZE>>1);
			port_num = sm->munit.io_idx;
			for(i = 0;i<8;i++)
				romid[i] = ReadFlashByte(addr+i);
			config = read_config_from_sensor(port_num,romid);
			
			g_buff_handle_master[cur_off++] = config;
		}
	}
	
	*ret_len = cur_off;
	

	return ERR_NO_ERR;
}
//--------------------------------------------------------------0x66,67,68

s16 handle_cmd_meas(u08*in_buf,u08*out_buf,u16*ret_len)
{
	u08	romid[8],i,port_num,temp;
	u16 cur_off = 0;
	u32	addr;

	list_node_t* pnode;
	st_xidx_list* xlist;
	list_node_t*pnode1; 
	st_sensor_mdata* sm; 

	if((in_buf[1]!=0xFF)||(in_buf[2]!=0xFF)) 
	{
		return -1; 
	} 
	if(g_buff_handle_master == NULL) 
	{
		return -2; 
	} 

	for (pnode = list_begin(&g_mapping_list); pnode != list_end(&g_mapping_list);pnode = list_next(pnode))
	{
		xlist = entry_list(pnode, st_xidx_list, node);

		g_buff_handle_master[cur_off++] = xlist->scnt+2;

		if(pnode == list_front(&g_mapping_list))
			g_buff_handle_master[cur_off++] = FLAG_PACK_START;
		else if(pnode == list_back(&g_mapping_list))
			g_buff_handle_master[cur_off++] = FLAG_PACK_END;
		else 
			g_buff_handle_master[cur_off++] = FLAG_PACK_INTE;

		g_buff_handle_master[cur_off++] = xlist->xidx;
		
		for (pnode1 = list_begin(&xlist->list); pnode1 != list_end(&xlist->list);pnode1 = list_next(pnode1))
		{
			sm = entry_list(pnode1, st_sensor_mdata, node);

			addr = (u32)sm->munit.rom_addr+(FLASH_SIZE>>1);
			port_num = sm->munit.io_idx;
			for(i = 0;i<8;i++)
				romid[i] = ReadFlashByte(addr+i);

			temp = read_temp_from_sensor(port_num,romid);
			
			g_buff_handle_master[cur_off++] = temp;
		}
	}
	
	*ret_len = cur_off;

	return ERR_NO_ERR;
}


s16 handle_master_cmd(u08*in_buf,u08*out_buf,u16* ret_len)
{
	u08 cmd;
	u16 ret = 0;
	u16 len;

	bit_clear(PORTA,BIT1);
	bit_clear(PORTA,BIT2);
	delayms(1);

	cmd = in_buf[0];
	switch(cmd)
	{
		case 0x60:
			ret = handle_cmd_querry_sensors(in_buf,out_buf,&len);
			break;
		case 0x62:
			ret = handle_cmd_search_sensors(in_buf,out_buf,&len);
			break;
		case 0x65:
			ret = handle_cmd_read_config(in_buf,out_buf,&len);
			break;
		case 0x66:
			ret = handle_cmd_meas(in_buf,out_buf,&len);         
			break;
		default:
			break;        
	}

	bit_set(PORTA,BIT1);
	bit_set(PORTA,BIT2);

	*ret_len = len;

	return ret;
}

